package core.util;

import java.io.IOException;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;

import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

public class PropertiesUtil {
	private static ConcurrentHashMap<String, Properties> map;
	static {
		try {
			init();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private static void init() throws IOException {
		ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
		Resource[] resources = resolver.getResources("classpath:*.properties");
		if (resources != null && resources.length > 0) {
			map = new ConcurrentHashMap<>(resources.length);
			for (Resource resource : resources) {
				Properties properties = new Properties();
				properties.load(resource.getInputStream());
				map.put(resource.getFilename().replaceAll(".properties", ""), properties);
			}
		}
	}

	public static void refresh() throws IOException {
		init();
	}

	public static String get(String key) {
		return get("config", key);
	}

	public static String get(String filename, String key) {
		Properties p = map.get(filename);
		if (p == null) {
			return null;
		}
		return p.getProperty(key);
	}

	public static String get(String filename, String key, String defaultValue) {
		Properties p = map.get(filename);
		if (p == null) {
			return defaultValue;
		}
		return p.getProperty(key);
	}
}
